package com.version.manager.service.Shop;

import com.version.manager.entity.Shop.shopCar;
import com.version.manager.mapper.Shop.shopCarMapper;
import com.version.manager.model.Msg;
import com.version.manager.rabbitmq.MQConfig;
import com.version.manager.rabbitmq.MQSender;
import com.version.manager.service.BaseService;
import com.version.manager.util.QueryParam;
import com.version.manager.util.RedisUtil;
import com.version.manager.vo.shopCarInput;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

import com.version.manager.util.DateTimeUtil;

@Service
@Transactional(rollbackFor = Exception.class)
public class shopCarService extends BaseService<shopCarMapper, shopCar> {

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private shopCarMapper mapper;
    @Autowired
    private MQSender mqSender;
    private static final String KEY_PREFIX="shop_car_cache";
    private static Logger logger= LoggerFactory.getLogger(shopCarService.class);

    /**
     * 将购物车数据保存到数据库
     * @param c
     */
    public void saveToDb(shopCar c){
        Map<String,Object> map=new HashMap<>();
        map.put("userId",c.getUserId());
        map.put("storeId",c.getStoreId());
        QueryParam queryParam=new QueryParam(map);

        List<shopCar> find=super.selectList(queryParam);
        if(find.size()==0){
            c.setId(UUID.randomUUID().toString());
            c.setCreateTime(DateTimeUtil.getStringDate());
            super.mapper.insert(c);
        }else{
            c.setId(find.get(0).getId());
            c.setUpdateTime(DateTimeUtil.getStringDate());
            super.mapper.updateByPrimaryKey(c);
        }
    }

    @Cacheable(value = "goodsPrice",key = "'goodsPrice'",sync=true)
    public   List<shopCar>getPrice(){
        return mapper.getPrice();
    }


    /**
     * 查询购物车数据
     * @param userId
     * @return
     */
    public Msg getCar(String userId){
        String key=KEY_PREFIX+"_"+userId;
        List<shopCar> cars=new ArrayList<>();
        Map<Object,Object> map=redisUtil.hmget(key);
        List<shopCar> prices=getPrice();
        if(map==null||map.size()==0){
            Map<String,Object> pmap=new HashMap<>();
            pmap.put("userId",userId);
            QueryParam queryParam=new QueryParam(pmap);
            cars=super.selectList(queryParam);
            for (shopCar it:cars){
                prices.forEach(k->{
                    if(k.getId().equals(it.getStoreId())){
                        it.setPrice(k.getPrice());
                    }
                });
                redisUtil.hset(key,it.getStoreId(),it);
            }
        }
        else{
            for(Object k:map.keySet()){
                shopCar item=(shopCar)map.get(k);
                cars.add(item);
            }
        }
        return Msg.success().addData(cars);

    }

    /**
     * 购物车单项加减操作
     * @param userId
     * @param storeId
     * @param count
     */
    public void  addminusItem(String userId,String storeId,int count){
        String key=KEY_PREFIX+"_"+userId;
        String carKey=storeId;
        shopCar car=(shopCar)redisUtil.hget(key,carKey);
        int status=count>0?1:0;
        if(car==null){
            Map<String,Object> map=new HashMap<>();
            map.put("userId",userId);
            map.put("storeId",storeId);
            QueryParam queryParam=new QueryParam(map);
            List<shopCar> list=super.selectList(queryParam);
            if(list.size()==0){
                return;
            }
            car=list.get(0);
        }
        car.setStatus(status);
        redisUtil.hset(key,carKey,car,3600);

        shopCarInput input=new shopCarInput();
        input.setCarItem(car);
        input.setUserId(userId);
        //发送到rabitmq队列
        mqSender.send(MQConfig.SHOP_CAR_QUEUE,input);

    }

    /**
     * 加入购物车
     * @param input
     */
    public void save(shopCarInput input){
        String key=KEY_PREFIX+"_"+input.getUserId();
        String carKey=input.getCarItem().getStoreId();
        shopCar car=input.getCarItem();
        redisUtil.hset(key,carKey,car,3600);

        //发送到rabitmq队列
        mqSender.send(MQConfig.SHOP_CAR_QUEUE,input);
    }
}
